--[[
@classmod History
]]

local lume = require(LIB_PATH .. "lume")

return pl.class {
   _name = "History",
   
   add_entry = function (self, entry)
      table.insert(self.entries, self.history_position, entry)
      self.history_position = #self.entries + 1
   end,
   
   go_up = function (self)
      self.history_position = lume.clamp(self.history_position - 1, 0, 
					 #self.entries+1)
      return self:get_current_entry ()
   end,
   
   go_down = function (self)
      self.history_position = lume.clamp(self.history_position + 1, 0, 
					 #self.entries+1)
      return self:get_current_entry ()
   end,
   
   get_current_entry = function (self)
      return self.entries[self.history_position] or ""
   end,

   save = function (self)
      local file, err = io.open(".history", "a")
      if err then return err end
      self.entries = lume.unique(self.entries)
      lume.each(self.entries, function (entry) file:write(entry.."\n") end)
      file:close()
   end,

   clear_file = function (self, filename)
      io.open(filename,"w"):close()
   end,

   load = function (self)
      local file, err = io.open(".history", "r")
      if not file then
	 file = io.open(".history", "w")
	 file:write()
      end
      for line in file:lines() do
	 table.insert(self.entries, line)
      end
      file:close()
      self.history_position = #self.entries + 1
   end,
   
   _init = function (self, init_val, max)
      self.entries = {}
      if init_val then table.insert(self.entries, init_val) end
      self:clear_file(".history")
      self:load()
      self.max_entries = max or 30
      self.history_position = 0
      self.entries[0] = ""
   end,

}
